/**
  * Author: Mei
  * Date: 2020-12-08 19:22
  * Description: 
  * 交替打印
  */
#include <thread>
#include <iostream>
#include <semaphore.h>
#include <mutex>
#include <condition_variable>

using namespace std;

class Foo {
private:
    sem_t first;
    sem_t second;
public:
    Foo() {
        sem_init(&first, 0, 0);
        sem_init(&second, 0, 0);
    }

    void printFist() {
        cout << "first" << endl;
        sem_post(&first);
    }

    void printSecond() {
        sem_wait(&first);
        cout << "second" << endl;
        sem_post(&second);
    }

    void printThird() {
        sem_wait(&second);
        cout << "third" << endl;
    }

};

class Foo1 {
private:
    mutex mu;
    condition_variable cond;
    bool flag = false;
    bool flag1 = false;
public:
    void printFist() {
        unique_lock<mutex> lock(mu);
        cout << "1" << endl;
        flag = true;
        cond.notify_one();
    }

    void printSecond() {
        unique_lock<mutex> lock(mu);
        if (flag == false) {
            cond.wait(lock);
        }
        cout << "2" << endl;
        flag1 = true;
        cond.notify_one();
    }

    void printThird() {
        unique_lock<mutex> lock(mu);
        if (flag1 == false) {
            cond.wait(lock);
        }
        cout << "3" << endl;
    }

};

int main() {
    Foo1 foo;
    thread f2{&Foo1::printSecond, &foo};
    thread f3{&Foo1::printFist, &foo};
    thread f{&Foo1::printThird, &foo};

    f.join();
    f2.join();
    f3.join();

    return 0;
}
